package com.summer.bilibili.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送
 */
@Slf4j
@Component
public class AppMailSender {
    @Resource
    private ThreadPoolTaskExecutor executor; // 线程池

    @Resource
    private JavaMailSender mailSender; // 邮件发送器

    @Value("${spring.mail.username}")
    private String mailSenderName; // 发件人

    /**
     * 异步发送邮件
     *
     * @param subject  主题
     * @param html     正文
     * @param receiver 接收人
     */
    public void sendAsync ( String subject , String html , String receiver , @Nullable Runnable onFail ) {
        executor.submit ( () -> { // 在异步线程池中执行
            MimeMessage mimeMessage = mailSender.createMimeMessage ( ); // 创建邮件对象
            try {
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper ( mimeMessage , true ); // 创建邮件帮助器
                mimeMessageHelper.setFrom ( mailSenderName ); //必须再指定一次发件人
                mimeMessageHelper.setTo ( receiver ); // 收件人
                mimeMessageHelper.setSubject ( subject ); // 主题
                mimeMessageHelper.setText ( html , true ); // 正文
                mailSender.send ( mimeMessage );// 发送邮件
                log.info ( "发送邮件成功, 收件人: {}" , receiver );
            } catch (Exception e) {
                log.warn ( "邮件发送失败, 收件人: {} 原因: {}" , receiver , e.getMessage ( ) );
                if ( onFail != null ) {
                    onFail.run ( ); // 运行失败回调
                }
            }
        } );
    }
}
